﻿using Duende.IdentityServer.Models;
using Duende.IdentityServer.Validation;
using Simple.Tools;
using SimpleSaas.Web.Common;
using SimpleSaas.Web.Common.redis;
using System.Collections.Specialized;

namespace SimpleSaasAuth.Configuration
{
	public class CustomIntrospectionRequestValidator : IIntrospectionRequestValidator
	{

		private readonly ITokenValidator _tokenValidator;
		private readonly IRedisClientService _redisCache;

		public CustomIntrospectionRequestValidator(ITokenValidator tokenValidator, IRedisClientService redisCache)
		{
			_tokenValidator = tokenValidator;
			_redisCache = redisCache;
		}
		public async Task<IntrospectionRequestValidationResult> ValidateAsync(NameValueCollection parameters, ApiResource api)
		{
			var token = parameters.Get("token");
			if (token == null)
			{
				return new IntrospectionRequestValidationResult
				{
					IsError = true,
					Api = api,
					Error = "missing_token",
					Parameters = parameters
				};
			}

			// validate token
			var tokenValidationResult = await _tokenValidator.ValidateAccessTokenAsync(token);

			// invalid or unknown token
			if (tokenValidationResult.IsError)
			{
				return new IntrospectionRequestValidationResult
				{
					IsActive = false,
					IsError = false,
					Token = token,
					Api = api,
					Parameters = parameters
				};
			}

			var _key = tokenValidationResult.Claims.FirstOrDefault(t => t.Type == "sub")?.Value;

			var accessToken = await _redisCache.GetAsync<TokenInfo>("seq:user:accesstoken:" + _key);

			if (SimpleCheck.IsNull(accessToken) || accessToken.ExprieTime < DateTime.Now)
			{
				//Log.Debug("Token已强制失效");
				return new IntrospectionRequestValidationResult
				{
					IsActive = false,
					IsError = false,
					Token = token,
					Api = api,
					Parameters = parameters
				};
			}

			return new IntrospectionRequestValidationResult
			{
				IsActive = true,
				IsError = false,
				Token = token,
				Claims = tokenValidationResult.Claims,
				Api = api,
				Parameters = parameters
			};
		}
	}
}